package com.javafxboot.util;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.javafxboot.entity.PrintUrl;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import java.awt.print.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Qj {

    public static void readPdf(PrintUrl data) throws Exception{
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        // 创建webclient
        WebClient webClient = new WebClient();
        // 取消 JS 支持
        webClient.getOptions().setJavaScriptEnabled(false);
        // 取消 CSS 支持
        webClient.getOptions().setCssEnabled(false);
        // 获取指定网页实体
//        try {
            HtmlPage page = (HtmlPage) webClient.getPage(data.getUrl());


            final HtmlForm form = page.getForms().get(0);
            String ApiKey = form.getInputByName("ApiKey").getDefaultValue();
            String Data = form.getInputByName("Data").getDefaultValue();
            String TimeStamp = form.getInputByName("TimeStamp").getDefaultValue();
            String Signature = form.getInputByName("Signature").getDefaultValue();


            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("ApiKey="+ApiKey+"&");
            stringBuilder.append("Data="+java.net.URLEncoder.encode(Data, "UTF-8")+"&");
            stringBuilder.append("TimeStamp="+TimeStamp+"&");
            stringBuilder.append("Signature="+Signature);

            System.out.println(stringBuilder.toString());
            String returnString = HttpClientUtil.sendHttpPostQj("https://external2.shopee.tw/ext/familymart/OrderPrint/OrderPrint.aspx", stringBuilder.toString());

            returnString = returnString.substring(returnString.indexOf("images"), returnString.indexOf("\" width=\"627\""));
            System.err.println(returnString);

            URL url1 = new URL("https://external2.shopee.tw/ext/familymart/OrderPrint/" + returnString);
            URLConnection uc = url1.openConnection();
            InputStream inputStream = uc.getInputStream();

            Date dNow = new Date( );
            SimpleDateFormat ft = new SimpleDateFormat ("yyyy\\MM\\dd\\");
            ft.format(dNow);

            isexitsPath(""+ft.format(dNow)+"\\pdf");

            FileOutputStream out = new FileOutputStream(ft.format(dNow)+"1.gif");
            int j = 0;
            while ((j = inputStream.read()) != -1) {
                out.write(j);
            }
            inputStream.close();
            File directory = new File("");//参数为空
            String courseFile = directory.getCanonicalPath();
            System.out.println(courseFile);
            ImageUtil.cutImage(new File(ft.format(dNow)+"1.gif"), new File(ft.format(dNow)+""+data.getOrderSn()+".gif"), 0,0,1290,2110);
            convert(ft.format(dNow)+""+data.getOrderSn()+".gif", ft.format(dNow)+""+data.getOrderSn()+".pdf");

            if(data.getIsPrint()){
                defaultPrintPDF(courseFile+"\\"+ft.format(dNow)+""+data.getOrderSn()+".pdf");
            }


//        }catch (Exception e) {
//            // TODO: handle exception
//        }
    }

    public static boolean isexitsPath(String path)throws InterruptedException{
        String [] paths=path.split("\\\\");
        StringBuffer fullPath=new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\\\");
            File file=new File(fullPath.toString());
            if(paths.length-1!=i){//判断path到文件名时，无须继续创建文件夹！
                if(!file.exists()){
                    file.mkdir();
                    System.out.println("创建目录为："+fullPath.toString());
                }
            }
        }
        File file=new File(fullPath.toString());//目录全路径
        if (!file.exists()) {
            return true;
        }else{
            return false;
        }
    }

    public static void convert(String source, String target) throws Exception {
        Document document = new Document();
        //设置文档页边距
        document.setMargins(0,0,0,0);
        FileOutputStream fos = null;
//        try {
            fos = new FileOutputStream(target);
            PdfWriter.getInstance(document, fos);
            //打开文档
            document.open();
            //获取图片的宽高
            Image image = Image.getInstance(source);
            float imageHeight=image.getScaledHeight();
            float imageWidth=image.getScaledWidth();
            //设置页面宽高与图片一致
            Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
            document.setPageSize(rectangle);
            //图片居中
            image.setAlignment(Image.ALIGN_CENTER);
            //新建一页添加图片
            document.newPage();
            document.add(image);
//        } catch (Exception ioe) {
//            System.out.println(ioe.getMessage());
//        } finally {
//            //关闭文档
            document.close();
//            try {
                fos.flush();
                fos.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    public static void defaultPrintPDF(String pdfPath) throws IOException, PrinterException {

        File file = new File(pdfPath);
        // 读取pdf文件
        PDDocument document = PDDocument.load(file);
        // 创建打印任务
        PrinterJob job = PrinterJob.getPrinterJob();

        job.setPageable(new PDFPageable(document));

        Paper paper = new Paper();
        // 设置打印纸张大小
        paper.setSize(283,425); // 1/72 inch
        // 设置打印位置 坐标
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
        // custom page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        // override the page format
        Book book = new Book();
        // append all pages 设置一些属性 是否缩放 打印张数等
        book.append(new PDFPrintable(document, Scaling.SCALE_TO_FIT), pageFormat, 1);
        job.setPageable(book);
        // 开始打印
        job.print();

    }
}
